package org.xi.sims.controller.common;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.xi.sims.common.Constants;
import org.xi.sims.common.result.Result;
import org.xi.sims.common.result.ResultCode;
import org.xi.sims.config.exception.CloudException;
import org.xi.sims.pojo.form.LoginForm;
import org.xi.sims.service.AdminService;
import org.xi.sims.service.StudentService;
import org.xi.sims.service.TeacherService;
import org.xi.sims.util.IAssert;
import org.xi.sims.util.XinUtil;

import javax.validation.constraints.NotNull;

/**
 * @author ：xi
 * @time ：Created in 21:53
 * @description：
 */
@CrossOrigin
@RestController
@RequestMapping("/api/login")
public class LoginController {
    @Autowired
    @Lazy
    private StudentService studentService;
    @Autowired
    @Lazy
    private TeacherService teacherService;
    @Autowired
    @Lazy
    private AdminService adminService;

    @PostMapping
    public Result login(@RequestBody @Validated @NotNull LoginForm form) {
        switch (form.getType()) {
            case 0:
                StpUtil.login(loginStudent(form), Constants.STUDENT);
                break;
            case 1:
                StpUtil.login(loginTecher(form), Constants.TEACHER);
                break;
            case 2:
                StpUtil.login(loginAdmin(form), Constants.ADMIN);
                break;
            default:
                throw new CloudException(ResultCode.USER_UNAUTHORIZED);
        }
        return Result.ok();
    }

    private int loginAdmin(LoginForm form) {
        return login(adminService.findByNumber(form.getNumber()), form).getId();
    }

    private int loginTecher(LoginForm form) {
        return login(teacherService.findByNumber(form.getNumber()), form).getId();
    }

    private int loginStudent(LoginForm form) {
        return login(studentService.findByNumber(form.getNumber()), form).getId();
    }

    private <E> E login(E e, LoginForm form) {
        if (XinUtil.noEqual(
                        XinUtil.Md5(form.getPassword()),
                        BeanUtil.getFieldValue(
                                IAssert.isNull(e, ResultCode.USER_UNAUTHORIZED),
                                "password")
        )) {
            throw new CloudException(ResultCode.USER_UNAUTHORIZED);
        }
        return e;
    }
}
